<?php
function comment($config){
    // 1.连接MySQL数据库服务器
    $link = mysql_connect($config['host'],$config['user'],$config['pwd']);
    // 2.判断是否连接正确
    if(!$link){
        die('连接失败');
    }
    // 3.选择数据库
    mysql_select_db($config['db']);
    // 4.设置字符集
    mysql_set_charset($config['char']);
}
function select($config,$table,$where='',$limit='',$filed='*'){
    comment($config);

    // 5.准备SQL语句
    $sql="select {$filed} from {$table} {$where} order by id {$limit}";
    // 6.发送SQL语句到MySQL服务器
    $res=mysql_query($sql);
    // 7.处理结果集
    $return = array();
    while($arr = mysql_fetch_assoc($res)){
        $return[] = $arr;
    }
    // 8.释放结果集资源，关闭数据库连接
    mysql_free_result($res);
    mysql_close();

    return $return;
}
function insert($config,$table,$post){
    comment($config);
    // 5.准备SQL语句
    $name = '';
    $str = '';
    foreach($post as $k=>$v){
        if($k != 'colId'){
            $name .= "$k,";
            $str .= "'{$v}',";
        }
    }
    $sql='insert into '.$table.'('.trim($name,',').') values('.trim($str,',').')';
    // 6.发送SQL语句到MySQL服务器
    $res=mysql_query($sql);
    $return = mysql_error();
    // 7.关闭数据库连接
    mysql_close();

    return $return;
}
function delete($config,$table,$get){
    comment($config);
    // 5.准备SQL语句
    $sql='delete from '.$table.' where id='.$get;
    // 6.发送SQL语句到MySQL服务器
    $res=mysql_query($sql);
    $return = mysql_error();
    // 7.关闭数据库连接
    mysql_close();

    return $return;
}
function update($config,$table,$post){
    comment($config);
    // 5.准备SQL语句
    $str = '';
    foreach($post as $k=>$v){
        if($k!='id' && $k!='colId' && $k!='apic'){
            $str .= "{$k} = '{$v}',";
        }
    }
    $sql='update '.$table.' set '.trim($str,',').' where id='.$post['id'];
    // 6.发送SQL语句到MySQL服务器
    $res=mysql_query($sql);
    $return = mysql_error();
    // 7.关闭数据库连接
    mysql_close();

    return $return;
}
function dispage($config,$table,$where = '',$filed = '*'){
    comment($config);
    // 5.准备SQL语句
    $sql="select count(*) from $table {$where}";
    // 6.发送SQL语句到MySQL服务器
    $res=mysql_query($sql);
    // 7.处理结果集
    $count = mysql_fetch_assoc($res);

    $everypage = 3;

    $maxpage = ceil($count['count(*)']/$everypage);

    $page = (isset($_GET['p']) && !empty($_GET['p']) && is_numeric($_GET['p']) 
             && $_GET['p'] >= 1 && $_GET['p'] <= $maxpage) ? $_GET['p'] : 1;
    $num = ($page - 1) * $everypage;
    $limit = "limit {$num},{$everypage}";
    $res2 = select($config,$table,$where,$limit,$filed);

    if($page > 1){
        $prev = $page- 1;
    }else{
        $prev = 1;
    }

    if($page < $maxpage){
        $next = $page + 1;
    }else{
        $next = $maxpage;
    }

    $arr = array();
    $arr[] = $prev;
    $arr[] = $next;
    $arr[] = $maxpage;
    $arr[] = $page;
    $arr[] = $res2;
    $arr[] = $count['count(*)'];
    // 8.释放结果集资源，关闭数据库连接
    mysql_free_result($res);
    //mysql_close();    //引用select函数已关闭一次

    return $arr;
}
?>